package com.mingtu.dzpatrol.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;


import com.mingtu.dzpatrol.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyClearEditText extends LinearLayout implements OnFocusChangeListener, TextWatcher, View.OnClickListener {
    /**
     * 删除按钮的引用
     */
    private Drawable mClearDrawable;
    /**
     * 控件是否有焦点
     */
    private boolean hasFoucs;

    private boolean isShow = false;
    private Drawable mLeftDrawable;
    private EditText editText;
    private ImageView ivClear;
    private ImageView ivLeft;
    private int bg_img;
    private String my_hint = "";
    private CheckBox cbPassword;

    public MyClearEditText(Context context) {
        super(context);
    }

    public MyClearEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        /**加载布局文件*/
        LayoutInflater.from(context).inflate(R.layout.layout_clear_edit_text, this, true);
        ivLeft = (ImageView) findViewById(R.id.iv_left);
        ivClear = (ImageView) findViewById(R.id.iv_clear);
        editText = (EditText) findViewById(R.id.edit_text);
        cbPassword = (CheckBox) findViewById(R.id.cb_password);

        cbPassword.setOnCheckedChangeListener(onCheckedChangeListener);
        ivClear.setOnClickListener(this);
        editText.setOnFocusChangeListener(this);
        editText.addTextChangedListener(this);
        /**获取属性值*/
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ClearEditText);
        /**标题相关*/
        bg_img = typedArray.getResourceId(R.styleable.ClearEditText_mDrawableLeft, R.mipmap.login_username);
        my_hint = typedArray.getString(R.styleable.ClearEditText_mHint);
        ivLeft.setBackgroundResource(bg_img);
        editText.setHint(my_hint);
        typedArray.recycle();

        InputFilter inputFilter = new InputFilter() {

            Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");

            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {

                Matcher matcher = pattern.matcher(charSequence);
                if (!matcher.find()) {
                    return null;
                } else {

                    return "";
                }

            }
        };
        editText.setFilters(new InputFilter[]{inputFilter});
    }

    /**
     * 晃动动画
     *
     * @param counts 1秒钟晃动多少下
     * @return
     */
    public static Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }


    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     *
     * @param visible
     */
    protected void setClearIconVisible(boolean visible) {
        int type = editText.getInputType();
        if (type == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) || type == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
            if (visible) {
                cbPassword.setVisibility(View.VISIBLE);
            } else {
                cbPassword.setVisibility(View.GONE);
            }
        } else if (type == InputType.TYPE_TEXT_VARIATION_PASSWORD) {
            if (visible) {
                ivClear.setVisibility(View.VISIBLE);
            } else {
                ivClear.setVisibility(View.GONE);
            }
        }

    }

    public void setTextLength(int length) {
        InputFilter[] filters = {new InputFilter.LengthFilter(length)};
        editText.setFilters(filters);
    }

    public void setInputType(int type) {
        editText.setInputType(type);
    }

    /**
     * 当ClearEditText焦点发生变化的时候，判断里面字符串长度设置清除图标的显示与隐藏
     */
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        this.hasFoucs = hasFocus;
        if (hasFocus) {
            setClearIconVisible(editText.getText().toString().trim().length() > 0);
        } else {
            setClearIconVisible(false);
        }
    }

    /**
     * 当输入框里面内容发生变化的时候回调的方法
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int count,
                              int after) {
        if (hasFoucs) {
            setClearIconVisible(s.length() > 0);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 设置晃动动画
     */
    public void setShakeAnimation() {
        this.startAnimation(shakeAnimation(5));
    }

    /**
     * 输入类型为普通文本
     */

    public void setTypeClassText() {
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
    }

    /**
     * 输入类型为数字文本
     */
    public void setTypeClassNumber() {
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
    }


    public void setTypeClassTextNumber() {
        editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

    /**
     * 显示为密码
     */
    public void setTypeTextPassword() {
        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

    public String getText() {
        return editText.getText().toString().trim();
    }

    public void setText(String s) {
        editText.setText(s);
    }

    public void setSelection(int i) {
        editText.setSelection(i);
    }

    public EditText getEditText() {
        return editText;
    }

    public void setEditText(EditText editText) {
        this.editText = editText;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_clear:
                editText.setText("");
                break;
            case R.id.cb_password:
                Boolean cbStatus = cbPassword.isChecked();//查看状态
                if (!cbStatus) {
                    cbPassword.setChecked(true);
                } else {
                    cbPassword.setChecked(false);
                }
                break;
        }
    }

    public CheckBox.OnCheckedChangeListener onCheckedChangeListener = new CheckBox.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (cbPassword.isChecked()) {
                /* show the password*/
//                editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                setSelection(getText().length());
            } else {
                /* hide the password */
//                editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                setSelection(getText().length());
            }

        }
    };

}
